//string转buffer
function Str2Bytes(str) {
    var pos = 0;
    var len = str.length;
    if (len % 2 != 0) {
      return null;
    }
    len /= 2;
    var hexA = new Array();
    for (var i = 0; i < len; i++) {
      var s = str.substr(pos, 2);
      var v = parseInt(s, 16);
      hexA.push(v);
      pos += 2;
    }
    return hexA;
  }
  // ArrayBuffer转16进度字符串示例
  function ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  }
//write
function writeBLECharacteristicValue(deviceId) {
    console.log('zs'+deviceId)
    // 向蓝牙设备发送一个0x00的16进制数据
    let x = Str2Bytes('03000000000000000000000000000000')
    var typedArray = new Uint8Array(x);
    var buffer = typedArray.buffer;
    ui.writeBLECharacteristicValue({
      deviceId: deviceId,
      serviceId:'000056FF-0000-1000-8000-00805F9B34FB',//监听 写数据
      characteristicId: '000033F3-0000-1000-8000-00805F9B34FB',
      value: buffer,
      success: (res) => {
        console.log( res)
      },
      fail: (res) => {
        ui.removeStorageSync('ble')
        console.log('连接失败')
        return false
      }
    })
  }
//获取步数
function getStep(str) {
        ///数据处
        var time = str.substr(2, 8)//时间
        var step = str.substr(10, 8)//步数
        var distance = str.substr(18, 8)//距离
        var calorie = str.substr(26, 8)//卡路里
        var sleep = str.substr(34, 6)//睡眠时间
        var array = [time, step, distance, calorie, sleep]
        var list = {};
        for (let i = 0; i < array.length; i++) {
            var g = array[i].substr(0, 2)
            var s = array[i].substr(2, 2)
            var b = array[i].substr(4, 2)
            var q = array[i].substr(6, 2)
            var sttr = q + b + s + g
            var num = parseInt(sttr,16)
            if(i == 0)list['time'] = num;
            if(i == 1)list['step'] = num;
            if(i == 2)list['distance'] = num;
            if(i == 3)list['calorie'] = num;
            if(i == 4)list['sleep'] = num;
        }
        return list
}

module.exports = {
    getStep: getStep,
    writeBLECharacteristicValue:writeBLECharacteristicValue,
}
